extends Node

@onready var tasks: Tasks = $'../../Tasks'
@onready var items: Items = $'../../Items'
@onready var player: Player = $'..'
@onready var hungerBar: ProgressBar = $'../HungerBar'

enum Action {
	idle,
	tasking,
}

var curAction: Action = Action.idle
var curTask: Task = null

var bag = []

# 饥饿度
var hungry: float = 0.4:
	set(val):
		hungry = clamp(val, 0, 1)
# 进食速度
var eatSpeed: float = 0.5
# 每帧饥饿的增值率
var hungryRate: float = 0.1
# 收获速度
var harvestSpeed: float = 1

func _physics_process(delta):
	renderHungryBar(delta)

	if curTask:
		doCurTask(delta)
	else:
		# 当饥饿时自动执行进食任务，否则执行其他一般任务
		# if hungry > 0.8:
		# 	curTask = tasks.getFindFoodTask()
		# else:
		curTask = tasks.getTask()

# 渲染饥饿进度条
func renderHungryBar(delta):
	hungry += hungryRate * delta
	hungerBar.value = hungry * 100

# 拾取
func pickUpItem(item):
	bag.append(item)
	items.remove(item)

# 检测当前是否空闲，空闲则执行当前子任务
func doCurTask(delta):
	var subTask = curTask.getCurrentTask()
	if curAction == Action.idle: return startCurSubTask(subTask)
	
	match subTask.type:
		Task.TaskType.walkTo:
			if player.isReached():
				curTask.reachedDestination()
				finishSubTask()

		Task.TaskType.eat:
			if bag[0].recovery > 0 and hungry < 1:
				bag[0].recovery -= eatSpeed * delta
				hungry -= eatSpeed * delta
			else:
				print('结束进食')
				bag.erase(bag[0])
				curTask.finishSubTask()
				finishSubTask()
		Task.TaskType.harvest:
			var targetItem = curTask.getCurrentTask().targetItem
			if targetItem.tryHarvest(harvestSpeed * delta):
				curTask.finishSubTask()
				finishSubTask()
			else:
				print('作物成熟进度：', targetItem.harvestState)

# 结束当前子任务
func finishSubTask():
	curAction = Action.idle
	if curTask.isFinished(): curTask = null

# 开始执行子任务
func startCurSubTask(subTask: Task):
	print('start SubTask:', subTask.TaskType.keys()[subTask.type])
	match subTask.type:
		Task.TaskType.fundItems:
			var targetItem = items.findNearstItem(subTask.itemType, player.position)
			if !targetItem:
				print('未找到食物，任务终止！')
				curTask.finish()
				curTask = null
				return
			curTask.foundItem(targetItem)
			finishSubTask()
		Task.TaskType.walkTo:
			player.moveTo(subTask.targetItem.position)
			curAction = Action.tasking
		Task.TaskType.pickUp:
			pickUpItem(subTask.targetItem)
			curTask.finishSubTask()
			finishSubTask()
		Task.TaskType.eat:
			print(bag)
			curAction = Action.tasking
		Task.TaskType.harvest:
			curAction = Action.tasking
